package nat_port_mapping

import (
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	devstar_cloud_provider_service_errors "code.gitea.io/gitea/services/devstar_cloud_provider/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	vpc "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vpc/v20170312"
)

// AssignDevstarCloudNATPortForwarding2TencentCloud 将增加 NAT 端口映射规则的任务派发到 Tencent Client
// API Doc: https://cloud.tencent.com/document/api/215/36720
func AssignDevstarCloudNATPortForwarding2TencentCloud(privatePort, publicPort uint64, portDescription string) error {
	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。
	// 以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := common.NewCredential(
		setting.Devstar.Cloud.Tencent.SecretId,
		setting.Devstar.Cloud.Tencent.SecretKey,
	)

	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = setting.Devstar.Cloud.Tencent.Endpoint
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := vpc.NewClient(credential, setting.Devstar.Cloud.Tencent.Region, cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := vpc.NewCreateNatGatewayDestinationIpPortTranslationNatRuleRequest()
	request.NatGatewayId = common.StringPtr(setting.Devstar.Cloud.Tencent.NatGatewayId)
	request.DestinationIpPortTranslationNatRules = []*vpc.DestinationIpPortTranslationNatRule{
		&vpc.DestinationIpPortTranslationNatRule{
			IpProtocol:       common.StringPtr(setting.Devstar.Cloud.Tencent.IpProtocol),
			PublicIpAddress:  common.StringPtr(setting.Devstar.Cloud.Tencent.PublicIpAddress),
			PublicPort:       common.Uint64Ptr(publicPort),
			PrivateIpAddress: common.StringPtr(setting.Devstar.Cloud.Tencent.PrivateIpAddress),
			PrivatePort:      common.Uint64Ptr(privatePort),
			Description:      common.StringPtr(portDescription),
		},
	}

	// 返回的resp是一个CreateNatGatewayDestinationIpPortTranslationNatRuleResponse的实例，与请求对象对应
	response, err := client.CreateNatGatewayDestinationIpPortTranslationNatRule(request)
	if err != nil {
		return devstar_cloud_provider_service_errors.ErrFailed2CreateNATRule{
			CloudProviderName: "Tencent",
			PortDescription:   portDescription,
			PrivatePort:       privatePort,
			PublicPort:        publicPort,
			Reason:            err.Error(),
		}
	}

	// 创建成功，打印留存 RequestId 同时返回 error=nil
	log.Info("Successfully created NAT Rule '%v': private port %v -> public port %v (Request ID: %v)",
		portDescription, privatePort, publicPort, response.Response.RequestId,
	)
	return nil
}
